import { useEffect, useRef } from 'react';
import StartGame from './game/main';
import styles from '@/index.module.less'
import { useSearchParams } from 'react-router';
import { EventBus } from '@/EventBus';
import { Button, Space } from 'antd';

export default function () {
  const game = useRef<Phaser.Game | null>(null!);
  const [searchParams] = useSearchParams()
  const nickName = searchParams.get('nickName')

  useEffect(() => {
    if (game.current === null) {
      game.current = StartGame("game-container");
    }

    function preventDefault(event:any) {
      event.preventDefault();
    }

    document.addEventListener('contextmenu',preventDefault);
    return () => {
      if (game.current) {
        game.current.destroy(true);
        if (game.current !== null) {
          game.current = null;
        }
      }
      document.removeEventListener('contextmenu',preventDefault)
    }
  }, [])

  function toMainScene() {
    EventBus.emit('toMainScene')
  }

  return (
    <div className={styles.container}>
      <Space className={styles.title}>
        <span>hello，{nickName}</span>
        <Button type='primary' onClick={toMainScene}>游戏开始</Button>
      </Space>
      <div id="game-container"></div>
    </div>
  )
}
